package com.jch.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Before;
import org.junit.Test;

public class HbaseApi {

    HBaseAdmin admin;
    Connection connection;


    @Before
    public void init() throws Exception{

        //建立连接
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","hadoop101,hadoop102,hadoop103");

        connection = ConnectionFactory.createConnection(conf);
        admin=(HBaseAdmin)connection.getAdmin();
    }


    //查看所有表
    @Test
    public void list() throws Exception{

        TableName[] table = admin.listTableNames();

        for (TableName t:table){
            System.out.println(t);
        }

    }

    //创建表
    @Test
    public void create() throws Exception{

        //表名
        TableDescriptorBuilder user_info = TableDescriptorBuilder.newBuilder(TableName.valueOf("user_info"));

        //列族
        ColumnFamilyDescriptor info = ColumnFamilyDescriptorBuilder.of(Bytes.toBytes("info"));
        ColumnFamilyDescriptor data = ColumnFamilyDescriptorBuilder.of(Bytes.toBytes("data"));

        //将表名和列族连接起来
        user_info.setColumnFamily(info);
        user_info.setColumnFamily(data);

        //构建表
        TableDescriptor build = user_info.build();
        admin.createTable(build);
    }

    //添加数据
    @Test
    public void addall() throws Exception{

        //获取表名
        Table user_info = connection.getTable(TableName.valueOf("user_info"));

        Put put = new Put(Bytes.toBytes("rk0001"));
        put.addColumn(Bytes.toBytes("info"),Bytes.toBytes("name"),Bytes.toBytes("zhangsan"));
        put.addColumn(Bytes.toBytes("info"),Bytes.toBytes("age"),Bytes.toBytes("18"));
        put.addColumn(Bytes.toBytes("data"),Bytes.toBytes("math"),Bytes.toBytes("80"));
        put.addColumn(Bytes.toBytes("data"),Bytes.toBytes("computer"),Bytes.toBytes("90"));

        user_info.put(put);

    }


    //删除表
    @Test
    public void drop() throws Exception{

        admin.disableTable(TableName.valueOf("test"));
        admin.deleteTable(TableName.valueOf("test"));
        System.out.println("删除成功");
    }



}
